# -*- coding: utf-8 -*- 
# @Time : 2022/5/17 13:36 
# @Author : Yinkay·Huang
# @File : gui.py
import csv
import os
import shutil
import tkinter
import tkinter as tk
import tkinter.ttk
from PIL import ImageTk, Image
from tkinter import messagebox, ttk, scrolledtext
from tkinter.messagebox import showinfo

import self

import NewSpyder

file_path = "..\\程序执行结果文件\\"
indexUrl = "http://www.xbiquge.la/"  # 首页url
novelUrl = ""


def download(novelUrl, lab):
    root4 = tkinter.Tk()
    root4.title('Yinkay的书荒拯救机')
    root4.geometry("800x450+400+200")
    flage2 = NewSpyder.downloadNovel(novelUrl, lab)
    if flage2 == 1:
        label = tkinter.Label(root4, text='下载成功！')
        btn2 = tkinter.Button(root4, text="Go!", command=lambda: [root4.destroy(), openBug()])
        btn2.place(relx=0.4, rely=0.7, relwidth=0.2, relheight=0.1)
    elif flage2 == 0:
        label = tkinter.Label(root4, text='下载失败')
        btn1 = tkinter.Button(root4, text="重试", command=lambda: [root4.destroy(), show2()])
        btn1.place(relx=0.4, rely=0.7, relwidth=0.2, relheight=0.1)
    label.pack()
    root4.mainloop()


def book(root3, lab):
    path = lab + '.csv'
    # 为列定义标识符
    columns = ('小说名', '作者', '简介')
    # 创建一个 Treeview 小部件
    tree = ttk.Treeview(root3,
                        columns=columns,
                        show='headings')
    # 指定列的标题
    tree.heading('小说名', text='小说名')
    tree.heading('作者', text='作者')
    tree.heading('简介', text='简介')

    # 生成用于在 Treeview 上显示的元组列表
    bookname = []
    with open(path, encoding="utf-8") as f:
        reader = csv.reader(f)
        for row in reader:
            rownum = [row[0], row[1], row[4], row[5]]
            bookname.append(rownum)
    contacts = []
    for n in bookname[1:]:
        contacts.append((f'{n[0]}', f'{n[1]}', f'{n[2]}', f'{n[3]}'))

    # 使用 Treeview 小部件的 insert() 方法一个一个地创建新项目
    for contact in contacts:
        tree.insert('', tk.END, values=contact)

    # 定义一个函数来处理 <> 事件。 当您选择一个或多个项目时，程序将显示一个消息框
    def item_selected(event):
        for selected_item in tree.selection():
            item = tree.item(selected_item)
            record = item['values']
            # show a message
            showinfo(title='Information', message=record[2])

    tree.bind('<<TreeviewSelect>>', item_selected)

    # 将 Treeview 小部件放在根窗口上
    tree.grid(row=0, column=2, sticky='nsew', rowspan=6, ipadx=20, pady=20)

    # 向 Treeview 小部件添加垂直滚动条
    scrollbar = ttk.Scrollbar(root3, orient=tk.VERTICAL, command=tree.yview)
    tree.configure(yscroll=scrollbar.set)
    scrollbar.grid(row=0, column=3, sticky='ns', rowspan=6)

    def color():
        for selected_item in tree.selection():
            item = tree.item(selected_item)
            record = item['values']
            root3.destroy()
            download(record[3], lab)
            print(record[3])

    theButton = tk.Button(root3, text="下载", command=color)
    theButton.grid(row=6, column=2, sticky='ew', columnspan=3)

    # 启动
    root3.mainloop()


def show3():
    root3 = tk.Tk()  # 创建窗口
    root3.title('Yinkay的书荒拯救机')
    root3.geometry("525x120+500+300")  # 长x宽+x*y
    root3.resizable(width=False, height=False)
    # 创建滚动条组件
    bar = scrolledtext.Scrollbar(root3, orient=tk.HORIZONTAL)  # orient设置水平
    bar.grid(row=2, column=1, sticky=(tk.W, tk.E), columnspan=3)  # 设置东西方向占满

    L1 = tkinter.Label(root3, text="书名(可空)：")
    L1.grid(row=0, column=0)
    E1 = tkinter.Entry(root3, width=55, xscrollcommand=bar.set)  # xscrollcommand和滚动条方法关联
    E1.grid(row=0, column=1, padx=10, pady=5, columnspan=3)
    L2 = tkinter.Label(root3, text="网        址：")
    L2.grid(row=1, column=0)
    E2 = tkinter.Entry(root3, width=55, xscrollcommand=bar.set)  # xscrollcommand和滚动条方法关联
    E2.grid(row=1, column=1, padx=10, pady=5, columnspan=3)
    bar.config(command=E1.xview)  # command和输入框组件关联

    b = tkinter.Button(root3, text='获取', padx=10, pady=5)
    b.grid(row=3, column=1)
    b2 = tkinter.Button(root3, text='清空', padx=10, pady=5)
    b2.grid(row=3, column=2)
    b3 = tkinter.Button(root3, text='返回', padx=10, pady=5,command=lambda: [root3.destroy(), openBug()])
    b3.grid(row=3, column=3)

    # 事件`a
    def getData(e):
        url = E2.get()
        lab = E1.get()
        if url != '' and lab != '':
            lab = '未知名小说'
            root3.destroy()
            NewSpyder.downloadNovel(url, lab)
        elif url != '' and lab == '':
            root3.destroy()
            NewSpyder.downloadNovel(url, lab)
        else:
            tkinter.messagebox.showerror('错误', '网址为空！！')
        print('获取数据：', E1.get())

    def deleteData(e):
        print('已清空')
        E1.delete(0, 'end')
        E2.delete(0, 'end')

    b.bind('<Button-1>', getData)
    b2.bind('<Button-1>', deleteData)

    root3.mainloop()

def show2():
    root3 = tk.Tk()  # 创建窗口
    root3.title('Yinkay的书荒拯救机')
    root3.geometry("800x475+400+200")  # 长x宽+x*y
    # root3.resizable(width=False, height=False)

    # 按钮1
    btn2 = tkinter.Button(root3, command=lambda: book(root3, "修真小说"))
    btn2["text"] = "修真小说"
    btn2.grid(column=0, row=0, ipadx=20, padx=20, pady=20)

    # 按钮2
    btn2 = tkinter.Button(root3, command=lambda: book(root3, "玄幻小说"))
    btn2["text"] = "玄幻小说"
    btn2.grid(column=0, row=1, ipadx=20, padx=20, pady=20)

    # 按钮3
    btn3 = tkinter.Button(root3, command=lambda: book(root3, "科幻小说"))
    btn3["text"] = "科幻小说"
    btn3.grid(column=0, row=2, ipadx=20, padx=20, pady=20)

    # 按钮4
    btn4 = tkinter.Button(root3, command=lambda: book(root3, "穿越小说"))
    btn4["text"] = "穿越小说"
    btn4.grid(column=0, row=3, ipadx=20, padx=20, pady=20)

    # 按钮5
    btn5 = tkinter.Button(root3, command=lambda: book(root3, "网游小说"))
    btn5["text"] = "网游小说"
    btn5.grid(column=0, row=4, ipadx=20, padx=20, pady=20)

    # 按钮6
    btn6 = tkinter.Button(root3, command=lambda: book(root3, "都市小说"))
    btn6["text"] = "都市小说"
    btn6.grid(column=0, row=5, ipadx=20, padx=20, pady=20)

    b2 = tkinter.Button(root3, text='返回', command=lambda: [root3.destroy(), openBug()])
    b2.grid(column=0, row=6, ipadx=20, padx=20, pady=20)

    root3.mainloop()

def show():
    flage = NewSpyder.run(self, indexUrl)
    root3 = tkinter.Tk()
    root3.title('Yinkay的书荒拯救机')
    root3.geometry("800x450+400+200")

    if flage == 1:
        label = tkinter.Label(root3, text='成功！')
        btn2 = tkinter.Button(root3, text="Go!", command=lambda: [root3.destroy(), openBug()])
        btn2.place(relx=0.4, rely=0.7, relwidth=0.2, relheight=0.1)
    elif flage == 0:
        label = tkinter.Label(root3, text='加载失败')
        btn1 = tkinter.Button(root3, text="重试", command=lambda: [root3.destroy(), openBug()])
        btn1.place(relx=0.4, rely=0.7, relwidth=0.2, relheight=0.1)
    label.pack()
    root3.mainloop()

def show4():
    lab = ['修真小说', '玄幻小说', '科幻小说', '穿越小说', '网游小说', '都市小说']
    for name in lab:
        path1 = '.\\' + name + '.csv'
        path2 = '..\\程序执行结果文件\\' + name + '图片'
        isExists1 = os.path.exists (path1)
        isExists2 = os.path.exists(path2)

        if isExists1:
            os.remove(path1)
        if isExists2:
            shutil.rmtree(path2)
            os.mkdir(path2)
    messagebox.showinfo('提示', '已清空！')

def show5():
    root3 = tk.Tk()  # 创建窗口
    root3.title('Yinkay的书荒拯救机')
    root3.geometry("525x120+500+300")  # 长x宽+x*y
    root3.resizable(width=False, height=False)

    L1 = tkinter.Label(root3, text="书名or作者：")
    L1.grid(row=0, column=0)
    E1 = tkinter.Entry(root3, width=55)  # xscrollcommand和滚动条方法关联
    E1.grid(row=0, column=1, padx=10, pady=5, columnspan=3)

    b = tkinter.Button(root3, text='获取', padx=10, pady=5)
    b.grid(row=3, column=1)
    b2 = tkinter.Button(root3, text='清空', padx=10, pady=5)
    b2.grid(row=3, column=2)
    b2 = tkinter.Button(root3, text='返回', padx=10, pady=5,command=lambda: [root3.destroy(), openBug()])
    b2.grid(row=3, column=3)

    # 事件`a
    def getData(e):
        lab = E1.get()
        if lab != '':
            NewSpyder.findtxt(lab)
            root3.destroy()

        else:
            tkinter.messagebox.showerror('错误', '书名为空！！')
        print('获取数据：', E1.get())

    def deleteData(e):
        print('已清空')
        E1.delete(0, 'end')

    b.bind('<Button-1>', getData)
    b2.bind('<Button-1>', deleteData)

    root3.mainloop()

# 功能选择
def openBug():
    root1 = tk.Tk()  # 创建窗口
    root1.title('Yinkay的书荒拯救机')

    root1.geometry("800x450+400+200")  # 长x宽+x*y

    root1.resizable(False, False)
    im_root = ImageTk.PhotoImage(Image.open('背景图片.jpg'))
    canvas_root = tkinter.Canvas(root1, width=800, height=450)
    canvas_root.create_image(220, 400, image=im_root)
    canvas_root.pack()

    # 创建按钮，并且将按钮放到窗口里面
    btn1 = tkinter.Button(root1, text="热榜小说爬取", command=lambda: [root1.destroy(),show()])
    btn1.place(relx=0.4, rely=0.85, relwidth=0.2, relheight=0.1)
    btn2 = tkinter.Button(root1, text="选择下载", command=lambda: [root1.destroy(), show2()])
    btn2.place(relx=0.4, rely=0.65, relwidth=0.2, relheight=0.1)
    btn3 = tkinter.Button(root1, text="直链下载", command=lambda: [root1.destroy(), show3()])
    btn3.place(relx=0.4, rely=0.45, relwidth=0.2, relheight=0.1)
    btn4 = tkinter.Button(root1, text="清空爬取信息", command=lambda: [show4()])
    btn4.place(relx=0.4, rely=0.25, relwidth=0.2, relheight=0.1)
    btn5 = tkinter.Button(root1, text="搜索下载", command=lambda: [root1.destroy(), show5()])
    btn5.place(relx=0.4, rely=0.05, relwidth=0.2, relheight=0.1)

    root1.mainloop()


openBug()
